using System;
using System.Data;
using System.Data.SqlClient;
using CoreLibrary.Sql;

namespace CoreLibrary.Messaging.Sql {

    public class InsertMessage : ISqlUpdator<bool> {

        private readonly string _tableName;
        private readonly Message _message;

        public InsertMessage(string tableName, Message message) {
            _tableName = tableName;
            _message = message;
        }

        public string GetSQL() {
            return string.Format(@"
                insert into {0} (id, aid, data, status, fault, retry, date_created, date_scheduled) 
                values( @Id, @Aid, @Data, @Status, @Fault, @Retry, @DateCreated, @DateScheduled
                );
            ", _tableName);
        }

        public void SetParameters(SqlCommand command) {
            var parms = command.Parameters;
            parms.Add("@Id",            SqlDbType.UniqueIdentifier).Value = new Guid(_message.Id);
            parms.Add("@Aid",           SqlDbType.Int).Value = (int)_message.ApplicationId;
            parms.Add("@Data",          SqlDbType.VarChar).Value = _message.Data;
            parms.Add("@Status",        SqlDbType.Int).Value = _message.Status;
            parms.Add("@Fault",         SqlDbType.VarChar).Value = _message.Fault;
            parms.Add("@Retry",         SqlDbType.Int).Value = _message.Retry;
            parms.Add("@DateCreated",   SqlDbType.DateTime).Value = _message.DateCreated;
            parms.Add("@DateScheduled", SqlDbType.DateTime).Value = _message.DateScheduled;
        }

        public bool GetResult(SqlConnection conn, int result) {
            return result > 0;
        }
    }
}